package shop.up.order.receiver;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import shop.up.common.constant.MqConst;
import shop.up.model.enums.OrderStatus;
import shop.up.model.enums.ProcessStatus;
import shop.up.model.order.OrderInfo;
import shop.up.order.service.OrderService;

import java.io.IOException;

/**
 * TODO {@link OrderReceiver}
 *
 * @author Kevin
 * @date 2022/7/30
 */
@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;

    /**
     * 监听消息
     * @param orderId
     * @param message
     * @param channel
     */
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId , Message message, Channel channel){
        try {
            if (orderId != null) {
                OrderInfo orderInfo = orderService.getOrderInfo(orderId);

                if (orderInfo != null
                        && OrderStatus.UNPAID.equals(orderInfo.getOrderStatus())
                        && ProcessStatus.UNPAID.equals(orderInfo.getProcessStatus())) {
                    // 取消订单
                    orderService.execExpiredOrder(orderId);
                    // 答复 broker
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
